<template>
  <div>
    <van-nav-bar title="充电中" left-text="返回" left-arrow @click-left="onClickLeft" />
  </div>

  <div style="margin-top: 40px;text-align: center;">
    <van-circle v-model:current-rate="currentRate" :rate="chargingRate" :speed="100" :text="text"></van-circle>
  </div>

  <van-loading vertical>
    <template #icon>
      <van-icon name="star" size="30" />
    </template>
  </van-loading>

  <div class="foot-div">
    <span><van-button round type="success" size="normal" @click="startCharging()">结束充电</van-button></span>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import router from '@/router';
import axios from 'axios';

const onClickLeft = () => history.back();

function startCharging() {
  axios.post('http://localhost:8812/car/stopCharg',null,{params: {id: 2}}).then(
      res => {
        if (res.data.code == 200){
          router.push('/charging/finish')
        }else {
          alert(res.data.errorMessage)
        }
      }
  )
}

var currentRate = ref(0); // 当前充电进度
var chargingRate = ref(0); // 初始充电进度
axios.defaults.withCredentials = true;

var token= localStorage.getItem("token");
axios.defaults.headers.common['Authorization'] = token;

// 更新电量的请求
const fetchChargingRate = async () => {
  try {
    const response = await axios.post('http://localhost:8812/car/carList');
    const newRate = response.data.data.data[0].electromagnetic;
    chargingRate.value = newRate;
    currentRate.value = newRate;
  } catch (error) {
    console.error('Request failed', error);
  }
};



// 定期获取充电电量
let intervalId;
onMounted(() => {
  fetchChargingRate(); // 页面加载时首次请求
  intervalId = setInterval(fetchChargingRate, 1000); // 每秒更新充电电量
});

onUnmounted(() => {
  clearInterval(intervalId); // 页面销毁时清除定时器
});

var text = computed(() => `${currentRate.value.toFixed(0)}%`);
</script>

<style>
.main-div {
  margin: 8px;
  height: 65px;
  width: auto;
  display: flex;
  border-radius: 2%;
  background-color: gray;
}

image {
  border-width: 0px;
  position: absolute;
  left: 0px;
  top: 0px;
}

.foot-div {
  margin-top: 100px;
  text-align: center;
}
</style>
